<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessage, ElMessageBox, ElDrawer } from "element-plus";
import Delete from "~icons/ep/delete";
import EditPen from "~icons/ep/edit-pen";
import Refresh from "~icons/ep/refresh";
import AddFill from "~icons/ri/add-circle-line";
import { getArticleList, addArticle, updateArticle, delArticle, auditArticle } from "@/api/article";
import { getArticleCategoryTree } from "@/api/article-category";
import ArticleForm from "./form.vue"; // 待创建
import type { ArticleFormData } from "./form.vue"; // 引入 ArticleFormData 接口

defineOptions({
  name: "ArticleList"
});

const formRef = ref();
const tableRef = ref();
const treeRef = ref();
const articleFormRef = ref(); // 新增：ArticleForm 组件的引用
const drawerVisible = ref(false);
const drawerTitle = ref("");
const formData = reactive<ArticleFormData>({
  // 指定 formData 的类型
  id: undefined,
  title: "",
  content: "",
  author: "",
  publish_time: "",
  category_id: null,
  status: 0,
  user_id: 1,
  image: "",
  description: "",
  tags: []
});
const auditDialogVisible = ref(false);
// 审核表单 */
const auditFormData = reactive({
  id: null,
  status: 0, // 0: 未审核, 1: 审核通过, 2: 审核未通过
  audit_reason: ""
});

const categoryName = ref("");
const form = reactive({
  title: "",
  status: null, // null: 全部, 0: 未审核, 1: 审核通过, 2: 审核未通过
  category_id: null
});
const loading = ref(false);
const dataList = ref<any[]>([]);
const categoryTree = ref<any[]>([]);
const selectedNum = ref(0);
const selectedRows = ref([]); // 新增：存储选中的行数据
const pagination = ref({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
// 获取文章列表
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      ...form
    };
    const { code, data, message, total } = await getArticleList(params);
    if (code !== 200) {
      ElMessage.error(message);
      return;
    }
    // 确保 data 是数组类型
    dataList.value = Array.isArray(data) ? data : data?.list || [];
    pagination.value.total = total || data?.total || 0;
  } catch (e) {
    ElMessage.error("获取文章列表失败");
    // 确保在错误情况下 dataList 是空数组
    dataList.value = [];
  } finally {
    loading.value = false;
  }
};
// 获取文章分类树
const fetchCategoryTree = async () => {
  const { code, data, message } = await getArticleCategoryTree();
  if (code !== 200) {
    ElMessage.error(message);
    return;
  }
  categoryTree.value = data;
};
// 搜索
const onSearch = () => {
  pagination.value.currentPage = 1;
  getList();
};
// 重置表单
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};
// 批量删除
const onbatchDel = () => {
  if (selectedNum.value === 0) {
    ElMessage.warning("请选择要删除的文章");
    return;
  }
  ElMessageBox.confirm(`是否确认删除选中的 ${selectedNum.value} 篇文章？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const ids = selectedRows.value.map(row => row.id);
    const { code, message } = await delArticle({ ids });
    if (code === 200) {
      ElMessage.success("批量删除成功");
      onSearch();
    } else {
      ElMessage.error(message);
    }
  });
};
// 单条删除
const handleDelete = row => {
  ElMessageBox.confirm(`是否确认删除文章标题为${row.title}的这条数据`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const { code, message } = await delArticle({ ids: [row.id] }); // 修改为传递数组
    if (code === 200) {
      ElMessage.success("删除成功");
      onSearch();
    } else {
      ElMessage.error(message);
    }
  });
};
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  onSearch();
};
const handleSelectionChange = val => {
  selectedNum.value = val.length;
  selectedRows.value = val; // 存储选中的行数据
};

const handleAudit = row => {
  auditDialogVisible.value = true;
  Object.assign(auditFormData, row);
};
// 提交审核表单
const handleAuditSubmit = async (formData: any) => {
  const { code, message } = await auditArticle(formData);
  if (code === 200) {
    ElMessage.success("操作成功");
    auditDialogVisible.value = false;
    await getList();
  } else {
    ElMessage.error(message);
  }
};

const openDrawer = async (title = "新增", row?: any) => {
  drawerVisible.value = true;
  drawerTitle.value = title;
  console.log("Opening drawer with row:", row); // Debug log to check row data

  // 每次打开抽屉时，先重置 formData
  formData.id = undefined;
  formData.title = "";
  formData.content = "";
  formData.author = "";
  formData.publish_time = "";
  formData.category_id = null;
  formData.status = 0;
  formData.user_id = 1;
  formData.image = "";
  formData.tags = [];

  // 等待下一个 tick 后重置表单组件
  await nextTick();
  if (articleFormRef.value) {
    articleFormRef.value.resetForm();
  }

  if (row) {
    // 如果是修改模式，则将行数据赋值给 formData
    Object.assign(formData, row);
  }
};

// 新增/修改提交表单
const handleSubmit = async (formData: any) => {
  const api = formData.id ? updateArticle : addArticle;
  console.log("Submitting form data:", formData); // Debug log to check formData
  const { code, message } = await api(formData);
  if (code === 200) {
    ElMessage.success("操作成功");
    drawerVisible.value = false;

    // 在成功提交后完全重置表单数据和状态
    formData.id = undefined;
    formData.title = "";
    formData.content = "";
    formData.author = "";
    formData.publish_time = "";
    formData.category_id = null;
    formData.status = 0;
    formData.user_id = 1;
    formData.image = "";
    formData.tags = [];

    // 重置表单组件状态
    if (articleFormRef.value) {
      articleFormRef.value.resetForm();
    }

    await getList();
  } else {
    ElMessage.error(message);
  }
};

const handleNodeClick = data => {
  form.category_id = data.id;
  onSearch();
};

onMounted(() => {
  fetchCategoryTree();
  getList();
});

watch(categoryName, val => {
  treeRef.value!.filter(val);
});

const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};

// 工具函数：根据背景色计算文字颜色
const getTextColor = (backgroundColor: string) => {
  if (!backgroundColor) return "#000000";
  const hex = backgroundColor.replace("#", "");
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness > 128 ? "#000000" : "#ffffff";
};
</script>

<template>
  <div class="main">
    <el-row :gutter="20">
      <el-col :span="4">
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入分类名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="treeRef"
            :data="categoryTree"
            :props="{ label: 'name' }"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20">
        <el-form
          ref="formRef"
          :inline="true"
          :model="form"
          class="search-form bg-bg_color w-full pl-8 pt-[12px] overflow-auto"
        >
          <el-form-item label="文章标题：" prop="title">
            <el-input v-model="form.title" placeholder="请输入文章标题" clearable class="w-[180px]!" />
          </el-form-item>
          <el-form-item label="状态：" prop="status">
            <el-select v-model="form.status" placeholder="请选择" clearable class="w-[180px]!">
              <el-option label="已发布" value="1" />
              <el-option label="草稿" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :icon="useRenderIcon('ri/search-line')"
              :loading="loading"
              @click="onSearch"
            >
              搜索
            </el-button>
            <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)"> 重置 </el-button>
          </el-form-item>
        </el-form>

        <div class="p-4 bg-bg_color">
          <div class="flex justify-between items-center mb-4">
            <p class="font-bold">文章列表</p>
            <div>
              <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="openDrawer('新增')">
                新增文章
              </el-button>
              <el-button
                type="danger"
                :icon="useRenderIcon(Delete)"
                :disabled="selectedNum === 0"
                @click="onbatchDel"
              >
                批量删除
              </el-button>
            </div>
          </div>
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="dataList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="文章封面" prop="image" width="160">
              <template #default="{ row }">
                <el-image
                  :src="row.image"
                  style="width: 100px; height: 60px; object-fit: cover"
                  :fit="'cover'"
                  :preview-src-list="[row.image]"
                  hide-on-click-modal
                  preview-teleported
                  :scale="0.8"
                >
                  <template #error>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        width: 100px;
                        height: 60px;
                        color: #999;
                        background-color: #f0f0f0;
                      "
                    >
                      无封面
                    </div>
                  </template>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="文章标题" prop="title" width="160" show-overflow-tooltip />
            <el-table-column label="作者" prop="author" />
            <el-table-column label="分类" prop="category_name" />
            <el-table-column label="标签" width="180">
              <template #default="{ row }">
                <div v-if="row.tags && row.tags.length > 0" class="tags-container">
                  <el-tag
                    v-for="tag in row.tags.slice(0, 3)"
                    :key="tag.id"
                    :color="tag.color"
                    :style="{
                      backgroundColor: tag.color,
                      color: getTextColor(tag.color),
                      borderColor: tag.color,
                      marginRight: '4px',
                      marginBottom: '2px'
                    }"
                    size="small"
                  >
                    {{ tag.name }}
                  </el-tag>
                  <el-tooltip
                    v-if="row.tags.length > 3"
                    :content="`还有 ${row.tags.length - 3} 个标签`"
                    placement="top"
                  >
                    <el-tag size="small" type="info">+{{ row.tags.length - 3 }}</el-tag>
                  </el-tooltip>
                </div>
                <span v-else class="text-gray-400">暂无标签</span>
              </template>
            </el-table-column>
            <el-table-column label="阅读量" prop="read_count" />
            <el-table-column label="评论数" prop="comment_count" />
            <el-table-column label="状态" width="110" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === 0 ? 'info' : row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 0 ? "未审核" : row.status === 1 ? "审核通过" : "审核未通过" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="简介" prop="description" show-overflow-tooltip />
            <el-table-column label="发布时间" prop="published_date" width="180" />
            <el-table-column label="操作" width="220" fixed="right" align="left">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  :icon="useRenderIcon(EditPen)"
                  @click="openDrawer('修改', row)"
                >
                  修改
                </el-button>
                <el-button link type="primary" :icon="useRenderIcon('ep:check')" @click="handleAudit(row)">
                  审核
                </el-button>
                <el-button link type="danger" :icon="useRenderIcon(Delete)" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="mt-4"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            background
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-row>
    <!--抽屉-->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="60%">
      <template #title>
        <div class="flex justify-between items-center">
          <p class="font-bold">{{ drawerTitle }}</p>
          <el-button type="text" @click="drawerVisible = false" />
        </div>
      </template>
      <ArticleForm
        ref="articleFormRef"
        :form-inline="formData"
        :category-tree-data="categoryTree"
        @submit="handleSubmit"
      />
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerVisible = false">取 消</el-button>
          <el-button type="primary" @click="articleFormRef.submitForm()">确 定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 审核弹窗 -->
    <el-dialog v-model="auditDialogVisible" title="审核文章" width="500px">
      <el-form ref="auditFormRef" :model="auditFormData" label-width="80px">
        <el-form-item label="审核结果">
          <el-select v-model="auditFormData.status">
            <el-option label="待审核" :value="0" />
            <el-option label="审核通过" :value="1" />
            <el-option label="审核未通过" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核理由">
          <el-input
            v-model="auditFormData.audit_reason"
            type="textarea"
            :autosize="{ minRows: 3 }"
            placeholder="请输入审核理由"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAuditSubmit(auditFormData)">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.tags-container .el-tag {
  height: 20px;
  padding: 0 6px;
  font-size: 11px;
  line-height: 18px;
  border-radius: 10px;
}
</style>
